/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Platform;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
/**
 *
 * @author tuantranle
 */
public class MyGame extends GameCanvas implements Runnable{
    
    private boolean isPlay;
    private long delay;
    private int currentX, currentY;
    private int width, height;
    private int scnX, scnY;
    private int state, activeFrame;
    private int speed;
    private int moveStep;
    private int widthFramePlayer, heightFramePlayer;
    private int margin;
    private int radius;
    //Layer 
    private LayerManager layerManager;
    
    //TiledLayer
    private TiledLayer tiledObs;
    private int []map = {
        1,0,0,0,
        0,0,0,0,
        0,2,0,0,
        0,0,0,0,
        0,0,0,0
    };
    
    //Sprite
    private Sprite playerSprite;
    private Sprite backgroundSprite;
    
    //Khởi tạo
    public MyGame() throws Exception{
        super(true);
        margin = 7;
        radius = 5;
        width = 240;
        height = 300;
        scnX = 0;
        scnY = 0;
        currentX = 180;
        currentY = 0;
        widthFramePlayer = 60;
        heightFramePlayer = 60;
        speed = 2;
        state = 0;
        delay = 20;
        
        //Load hình ảnh nhân vật
        Image image = Image.createImage("Images/man2.png");
        playerSprite = new Sprite(image,widthFramePlayer,heightFramePlayer);
     
        //Load hình ảnh nền
        Image background = Image.createImage("Images/background2.jpg");
        backgroundSprite = new Sprite(background);
        
        //Load vật cản
        tiledObs = initTiledObs();
        
        layerManager = new LayerManager();
        layerManager.append(playerSprite);
        layerManager.append(tiledObs);
        layerManager.append(backgroundSprite);      
    }
    
    public void start(){
        isPlay = true;
        Thread t = new Thread(this);
        t.start();
    }
    
    public void stop(){
        isPlay = false;
    }
    
    public void run(){
        Graphics g = getGraphics();
        while(isPlay == true){
            update();
            drawScreen(g);
            try{
                Thread.sleep(delay);
            }
            catch(InterruptedException ie){
            }
        }
    }

   private void update() {
        int keyStates = getKeyStates();
        
        //Chuyển frame hình về vị trí đứng im của nhân vật theo hướng di chuyển cuối cùng
        playerSprite.setFrame(ConvertMatrixToArray(state,0,5));
        
        //Di chuuyển trái
        if((keyStates & LEFT_PRESSED) != 0){
            if(state != 3){
                state = 3;
                activeFrame = 0;
                moveStep = 0;
            }
            //Xét va chạm với vật cản bên trái
            if(!checkCollision(currentX -speed +margin, currentY +margin +radius, map) && 
                    !checkCollision(currentX -speed +margin, currentY -margin +heightFramePlayer,map)){
                currentX = Math.max(scnX, currentX -speed);
            }
            MoveChangeFrame(5);    
        }
        
        //Di chuyển phải
        if((keyStates & RIGHT_PRESSED) != 0){
            if(state != 1){
                state = 1;
                activeFrame = 0;
                moveStep = 0;
            }
            //Xét va chạm với vật cản bên phải và khung hình
            if(currentX + 60 <= width &&
                    !checkCollision(currentX -margin+ widthFramePlayer +speed,currentY +margin +radius,map) &&
                    !checkCollision(currentX -margin+ widthFramePlayer +speed,currentY -margin +heightFramePlayer,map)){
                currentX = Math.min(width - 60, currentX + speed);
            }
            MoveChangeFrame(5);
            
        }
        
        //Di chuyển lên 
        if((keyStates & UP_PRESSED) != 0){
            if(state != 0){
                state = 0;
                activeFrame = 0;
                moveStep = 0;
            }
            //Xét va chạm với vật cản phía trên
            if(!checkCollision(currentX +margin, currentY +margin +radius -speed,map) &&
                    !checkCollision(currentX -margin +widthFramePlayer,currentY +margin +radius -speed,map)){
                currentY = Math.max(scnY, currentY - speed);
            }
            MoveChangeFrame(5);
        }
        
        //Di chuyển xuống
        if((keyStates & DOWN_PRESSED) != 0){
            if(state != 2){
                state = 2;
                activeFrame = 0;
                moveStep = 0;
            }
            if(currentY + 60 <= height &&
                    !checkCollision(currentX +margin,currentY -margin +heightFramePlayer +speed,map) &&
                    !checkCollision(currentX -margin + widthFramePlayer,currentY -margin +heightFramePlayer +speed,map)){
                currentY = Math.min(height - 60, currentY + speed);
            }
            MoveChangeFrame(5);
        }
    }

    private void drawScreen(Graphics g) {
        g.setColor(0,0,0);
        g.fillRect(0, 0, getWidth(), getHeight());

        playerSprite.setPosition(currentX, currentY);
        
        layerManager.setViewWindow(scnX, scnY, width, height);
        layerManager.paint(g, 0, 1);
  
        
        flushGraphics();
    }
    
    //Chuyển ma trận thành mảng 1 chiều
    private int ConvertMatrixToArray(int row, int column, int maxColumn){

        if(column >= maxColumn){
            activeFrame = column = 0;
        }
        return maxColumn*row + column;
    }
    
    //Tốc độ chuyển frame hình khi di chuyển
    private void MoveChangeFrame(int maxColumn){
        moveStep++;
        if(moveStep >= maxColumn-speed){
            activeFrame++;
            moveStep = 0;
        }
        playerSprite.setFrame(ConvertMatrixToArray(state ,activeFrame ,maxColumn ));        
    }
    
    //Chuyển từ tọa x sang tọa độ cột ma trận
    private boolean checkCollision(int posX, int posY, int []matrix){
        int column = posX / widthFramePlayer;
        int row = posY / heightFramePlayer;
        int index = row*(width/widthFramePlayer) + column;
        if(matrix[index]== 1 || matrix[index] == 2){
            return  true;
        }
        return false;
    }

    private TiledLayer initTiledObs() throws Exception {
        
        Image imageObs = Image.createImage("Images/obs.png");
        TiledLayer layer = new TiledLayer(width/widthFramePlayer,height/heightFramePlayer,imageObs,widthFramePlayer,heightFramePlayer);
        
        for(int i=0; i<map.length;i++){
            int column = i%(width/widthFramePlayer);
            int row = (i - column)/(height/heightFramePlayer - 1);
            layer.setCell(column, row, map[i]);
        }
        return layer;
        
    }
}
